#pragma once

#include <mysql/mysql.h>
#include <stdint.h>
#include <vector>
#include <map>
#include "Field.h"

class QueryResult
{
public:
    using FieldNames = std::map<uint32_t,std::string>;

    QueryResult(MYSQL_RES* result,uint64_t rowCount,uint32_t fieldCount);
    virtual ~QueryResult();

    Field* fetch() const { return m_currentRow; }
    uint32_t getFieldCount() const { return m_fieldCount; }
    uint64_t getRowCount() const { return m_rowCount; }
    FieldNames getFieldNames() const { return m_fieldNames; };
    std::vector<std::string> const& getNames() const { return m_vecFieldNames; }

    virtual bool nextRow();
    void endQuery();


    uint32_t getField_idx(const std::string &name) const
    {
        for(FieldNames::const_iterator iter = m_fieldNames.begin();iter!=m_fieldNames.end();++iter)
        {
            if(iter->second == name)
            {
                return iter->first;
            }
        }
    }

    const Field& operator[](int index) const
    {
        return m_currentRow[index];
    }

    const Field& operator[](const std::string& name) const
    {
        return m_currentRow[getField_idx(name)];
    }

private:
    Field::DataTypes convertNativeType(enum_field_types mysqlType) const;

private:
    Field*                      m_currentRow;
    uint32_t                    m_fieldCount;
    uint64_t                    m_rowCount;
    FieldNames                  m_fieldNames;
    std::vector<std::string>    m_vecFieldNames;
    MYSQL_RES*                  m_result;

};